<?php

namespace Gaolei\YiiRBAC\models\map;

use Yii;
use Gaolei\YiiRBAC\components\Configs;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

/**
 * Adminer model
 *
 * @property integer $id
 * @property string $username
 * @property string $realname
 * @property string $phone
 * @property integer $level
 * @property integer $state
 * @property string $auth_key
 * @property string $password_hash
 * @property integer $created_at
 * @property integer $updated_at
 */
class Adminer extends ActiveRecord
{

    const STATE_ACTIVE = 1;
    const STATE_DISABLE = 2;

    public static function states(): array
    {
        return [
            self::STATE_ACTIVE => '正常',
            self::STATE_DISABLE => '禁用',
        ];
    }

    const LEVE_NORMAL = 1;
    const LEVE_ADMIN = 6;
    const LEVE_SUPER = 99;

    public static function levels(): array
    {
        return [
            self::LEVE_NORMAL => '普通管理员',
            self::LEVE_ADMIN => '网站管理员',
            self::LEVE_SUPER => '超级管理员',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName(): string
    {
        return Configs::instance()->userTable;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '登录名',
            'realname' => '姓名',
            'phone' => '手机号码',
            'level' => '权限登陆',
            'state' => '账户状态',
            'created_at' => '添加时间',
            'updated_at' => '修改时间',
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['state', 'in', 'range' => [static::STATE_ACTIVE, static::STATE_DISABLE]],
        ];
    }

    /**
     * 根据user_backend表的username获取用户
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * 验证密码
     * @param string $password
     * @return bool
     */
    public function validatePassword(string $password): bool
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * @param string $password
     * @throws \yii\base\Exception
     */
    public function setPassword(string $password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * @throws \yii\base\Exception
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    public static function getDb()
    {
        return Configs::userDb();
    }
}
